<?php
/**
 * InventoryAllot.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-05-18 18:05:43
 * @modified    2023-05-18 18:05:43
 *
 */

namespace App\Models;

use App\Models\InventoryAllot\Item;
use App\Repositories\InventoryRepo;

class InventoryAllot extends BaseModel
{
    protected $table = 'inventory_allot';
    protected $primaryKey = 'id';

    public $timestamps = true;
    public const CREATED_AT = 'create_time';
    public const UPDATED_AT = 'update_time';

    protected $fillable = [
        'number',
        'source_warehouse_id',
        'target_warehouse_id',
        'target_user_id',
        'create_user_id',
        'audit_user_id',
        'status',
        'type',
        'description'
    ];

    protected $appends = [
        'status_text',
        'type_text'
    ];

    public function getStatusTextAttribute()
    {
        $status = collect(InventoryRepo::STATUS)->keyBy('code')->toArray();
        $current = $status[$this->status] ?? [];
        return $current['text'] ?? '';
    }

    public function getTypeTextAttribute()
    {
        $types = collect(InventoryRepo::TYPES)->keyBy('code')->toArray();
        $current = $types[$this->type] ?? [];
        return $current['text'] ?? '';
    }

    public function scopeByNumber($query, $number)
    {
        return $query->where('number', $number);
    }

    public function items()
    {
        return $this->hasMany(Item::class);
    }

    public function source_warehouse()
    {
        return $this->belongsTo(Warehouse::class, 'source_warehouse_id', 'id');
    }

    public function target_warehouse()
    {
        return $this->belongsTo(Warehouse::class, 'target_warehouse_id', 'id');
    }

    public function user()
    {
        return $this->belongsTo(UserModel::class, 'create_user_id', 'id');
    }

    public function target_user()
    {
        return $this->belongsTo(UserModel::class, 'target_user_id', 'id');
    }
}